package com.jumi.microservice.material.service.impl;

import com.alibaba.excel.EasyExcel;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.material.domain.JmMaterialAttributeVo;
import com.jumi.microservice.material.exception.excelException.ImportContentExistedException;
import com.jumi.microservice.material.exception.excelException.ValueExistedException;
import com.jumi.microservice.material.listener.excelListener.GoodsTaxExcelListener;
import com.jumi.microservice.material.service.ExcelService;
import com.jumi.microservice.material.listener.excelListener.AttrExcelListener;
import com.jumi.microservice.material.vo.JmGoodsTaxVo;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @description: Excel服务接口实现
 * @author: ZhangY
 */
@Service
public class ExcelServiceImpl implements ExcelService {

    @Resource
    private JmMaterialAttributeServiceImpl attributeService;

    @Resource
    private GoodsTaxServiceImpl goodsTaxService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult excelAttrsImport(HttpServletRequest request, Long uid, String name)
    {
        try
        {
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(request.getInputStream(), JmMaterialAttributeVo.class, new AttrExcelListener(attributeService,uid,name)).sheet().doRead();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return ResponseResult.error("解析异常,请检查上传格式");
        }catch (ImportContentExistedException | ValueExistedException e){
            return ResponseResult.error(e.getMessage());
        }
        return ResponseResult.success("ok");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult excelGoodsTaxsImport(HttpServletRequest request, Long uid, String name)
    {
        try
        {
            EasyExcel.read(request.getInputStream(), JmGoodsTaxVo.class, new GoodsTaxExcelListener(goodsTaxService,uid,name)).sheet().doRead();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return ResponseResult.error("解析异常");
        }
        return ResponseResult.success("ok");
    }

}
